<?php

namespace Modules\Admin\Http\Controllers\ActivationCodes;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\Models\ActivationCodeUsage;
use Modules\Common\Models\ActivationCodeLogs;
use Modules\Common\Models\ActivationCodes;
use Modules\Common\Models\SubscriptionRecords;
use Modules\Common\Models\SubscriptionTypes;
use Modules\Common\Models\Members;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;
use Carbon\Carbon;

class Activation
{
    /**
     * @Route(path=/api/admin/volume-activation  method=post)
     */
    public function index()
    {
        $adminUserIdDefault = auth('api')->user()->id;
        $eidDefault = auth('api')->user()->eid; 
        $sidDefault = auth('api')->user()->sid; 
        $user_ids_string = request('user_ids');
        $subscription_type_id = request('subscription_type_id');
        $auto_renew = request('auto_renew', '2');
    
        // 参数验证
        if (empty($user_ids_string) || empty($subscription_type_id)) {
            return Api::fail('Missing or invalid parameters', 400);
        }
    
        // 使用 explode 函数将字符串分割成数组
        $user_ids = explode(',', $user_ids_string);
        $user_ids = array_filter(array_map('trim', $user_ids));
    
        // 检查订阅类型是否存在
        $subscriptionType = SubscriptionTypes::find($subscription_type_id);
        if (!$subscriptionType) {
            return Api::fail('订阅类型不存在', 404);
        }
    
        DB::beginTransaction();
        try {
            foreach ($user_ids as $user_id) {
                $userId = intval($user_id);
                $member = Members::where('user_id', $userId)->first();

                if ($member) {
                    // 确保 end_date 是 Carbon 实例
                    $currentEndDate = Carbon::parse($member->end_date);
                                     
                    // 如果会员记录存在且还未到期，更新到期日期
                    if ($currentEndDate->gt(Carbon::now())) {
                        if ($subscriptionType->duration == -1) {
                            // 如果新订阅是永久的，设置为特定远期日期
                            $newEndDate = Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay();
                            
                        } else {
                            // 否则在现有基础上增加时长
                            if($currentEndDate = "9999-12-31 00:00:00"){
                                $newEndDate = Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay();
                            }else{
                                $newEndDate = $currentEndDate->addDays($subscriptionType->duration);
                            }
                        }
                    } else {
                        // 如果会员已经到期，设置新的开始和结束日期
                        $newEndDate = now();
                        if ($subscriptionType->duration == -1) {
                            $newEndDate = Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay();
                        } else {
                            if($currentEndDate = "9999-12-31 00:00:00"){
                                $newEndDate = Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay();
                            }else{
                                $newEndDate = $currentEndDate->addDays($subscriptionType->duration);
                            }
                        }
                    }
                    
                    // 更新会员记录
                    $member->update([
                        'level_id' => $subscriptionType->id,
                        'status' => 1,
                        'payment_method' => 3,
                        'subscription_type_id' => $subscriptionType->id,
                        'membership_fee' => $subscriptionType->price,
                        'auto_renew' => $auto_renew,
                        'start_date' => now(),
                        'end_date' => $newEndDate,
                    ]);
                } else {
                    // 如果不存在，创建新的会员记录
                    $member = Members::create([
                        'user_id' => $userId,
                        'level_id' => $subscriptionType->id,
                        'status' => 1,
                        'payment_method' => 3,
                        'subscription_type_id' => $subscriptionType->id,
                        'membership_fee' => $subscriptionType->price,
                        'auto_renew' => $auto_renew,
                        'start_date' => now(),
                        'end_date' => $subscriptionType->duration == -1 ? Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay() : now()->addDays($subscriptionType->duration),
                    ]);
                }
    
                // 创建批量激活订阅的记录
                $subscriptionRecordData = [
                    'user_id' => $userId,
                    'subscription_type_id' => $subscriptionType->id,
                    'start_date' => now(),
                    'end_date' => $subscriptionType->duration == -1 ? Carbon::createFromFormat('Y-m-d', '9999-12-31')->startOfDay() : now()->addDays($subscriptionType->duration),
                    'status' => 1,
                    'admin_user_id' => $adminUserIdDefault,
                    'eid' => $eidDefault,
                    'sid' => $sidDefault,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
                
                // 直接创建新的订阅记录，忽略是否存在匹配的记录
                $subscriptionRecord = SubscriptionRecords::create($subscriptionRecordData);
            }
    
            DB::commit();
            return Api::success(['message' => '会员批量激活成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            return Api::fail($e->getMessage(), 500);
        }
    }

}